package com.banciyuan.bcywebview.biz.search;

import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.base.factory.TimelineFactory;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreashRecycleView;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshBase;
import com.banciyuan.bcywebview.base.view.recycleview.OnResultScrollListener;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.string.StringUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.daoexample.model.AcgItem;
import de.greenrobot.daoexample.model.SearchContent;
import de.greenrobot.daoexample.model.TagItem;
import de.greenrobot.daoexample.model.Timeline;

/**
 * Created by squall on 2015/9/7.
 */
public class SearchContentFragment extends SearchBaseFragment {


    private PullToRefreashRecycleView mRefreshLv;
    private RecyclerView mContentLv;
    private LinearLayout ll_nodata;
    private String filter_name = "content";
    private List<SearchContent> slist = new ArrayList<>();
    private SearchContentAdapter mAdapter;

    private List<SearchContent> userList = new ArrayList<>();
    private List<SearchContent> tagsList = new ArrayList<>();
    private List<SearchContent> contentList = new ArrayList<>();

    private boolean isDataEnd;
    private boolean isWorkEnd;
    private boolean isUserEnd;

    private String userCount;
    private int tagCount;
    private int workCount;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View viewroot = inflater.inflate(R.layout.search_content_fragment, null);
        initArgs();
        initProgressbar(viewroot);
        initUi(viewroot);
        initAction();
        return viewroot;
    }

    @Override
    protected void initArgs() {
        Bundle args = getArguments();
        query = args.getString("query");
        filter_name = args.getString("filter");
    }

    @Override
    public void fetchData() {
        initData();
    }

    @Override
    protected void initUi(View rootview) {
        mRefreshLv = (PullToRefreashRecycleView) rootview.findViewById(R.id.search_refresh_lv);
        mContentLv = mRefreshLv.getRefreshableView();
        ll_nodata = (LinearLayout) rootview.findViewById(R.id.discover_search_nodata_layout);

        initAdapter();
        initRecyclerView();
        mContentLv.setAdapter(mAdapter);
    }

    private void initRecyclerView() {
        GridLayoutManager layout = new GridLayoutManager(getActivity(), 3);
        layout.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                switch (mAdapter.getItemViewType(position)) {
                    case SearchContentAdapter.COS_TYPE:
                    case SearchContentAdapter.WRITE_TYPE:
                    case SearchContentAdapter.DAILY_TYPE:
                    case SearchContentAdapter.GOODS_TYPE:
                        return 1;
                    default:
                        return 3;
                }
            }
        });
        RecyclerView.ItemAnimator animator = mContentLv.getItemAnimator();
        if (animator instanceof SimpleItemAnimator) {
            ((SimpleItemAnimator) animator).setSupportsChangeAnimations(false);
        }
        mContentLv.setLayoutManager(layout);
    }

    @Override
    protected void initAction() {
        mRefreshLv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<RecyclerView>() {
            @Override
            public void onRefresh(PullToRefreshBase<RecyclerView> refreshView) {
                clearTemp();
                loading = false;
                end_flag = false;
                page = 1;
                initData();
            }
        });

        mContentLv.addOnScrollListener(new OnResultScrollListener() {
            @Override
            public void onBottom() {
                if (!end_flag && !loading) {
                    page++;
                    contentList.clear();
                    isDataEnd = false;
                    initData();
                }
            }
        });
    }

    private void clearTemp() {
        isDataEnd = false;
        isWorkEnd = false;
        isUserEnd = false;
        userList.clear();
        tagsList.clear();
        contentList.clear();
    }


    private void getContent() {
        SearchHelper searchHelper = new SearchHelper(getActivity(), new ISearchhelper() {
            @Override
            public void succ(String type, String succ) {
                try {
                    Gson gson = new Gson();
                    JSONObject response = new JSONObject(succ);
                    JSONObject data = response.getJSONObject(HttpUtils.UPLOAD_DATA);
                    JSONArray results = data.getJSONArray("results");
                    if (page == 1) {
                        String count = data.getString("total");
                        SearchContent searchContent = new SearchContent();
                        searchContent.setTitle_num_format(String.format(getString(R.string.releated_content_pink), count));
                        searchContent.setIs_show(true);
                        contentList.add(searchContent);
                    }
                    List<Timeline> timelineList = gson.fromJson(results.toString(), new TypeToken<List<Timeline>>() {
                    }.getType());
                    List<Timeline> result = SearchHelper.popIllegal(timelineList, new int[]{TimelineFactory.TIMELINE_TYPE_COSER,
                            TimelineFactory.TIMELINE_TYPE_DAILY, TimelineFactory.TIMELINE_TYPE_WRITER, TimelineFactory.TIMELINE_TYPE_ILLUST, TimelineFactory.TIMELINE_TYPE_GOODS});
                    contentList.addAll(saveToInnerList(result));
                    isDataEnd = true;
                    checkEnd();
                } catch (Exception e) {
                    isDataEnd = true;
                    checkEnd();
                }
            }

            @Override
            public void fail(String type) {
                mProgressbarHelper.onFailed();
            }
        });
        searchHelper.getSearch("content", page, query);
    }

    private void getWork() {
        SearchHelper searchHelper = new SearchHelper(getActivity(), new ISearchhelper() {
            @Override
            public void succ(String type, String succ) {
                try {
                    List<SearchContent> templist = new ArrayList<>();
                    Gson gson = new Gson();
                    JSONObject response = new JSONObject(succ);
                    JSONObject data = response.getJSONObject(HttpUtils.UPLOAD_DATA);
                    JSONArray results = data.getJSONArray("results");
                    List<AcgItem> acgItemList = gson.fromJson(results.toString(), new TypeToken<List<AcgItem>>() {
                    }.getType());
                    for (AcgItem a : acgItemList) {
                        SearchContent searchContent1 = new SearchContent(a);
                        searchContent1.setOtype("work");
                        templist.add(searchContent1);
                    }
                    workCount = data.getInt("total");
                    getTags(templist);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void fail(String type) {
                mProgressbarHelper.onFailed();
            }
        });
        searchHelper.getSearch("work", page, query);
    }

    private void getTags(final List<SearchContent> wlist) {
        SearchHelper searchHelper = new SearchHelper(getActivity(), new ISearchhelper() {
            @Override
            public void succ(String type, String succ) {
                try {
                    tagsList.addAll(wlist);
                    Gson gson = new Gson();
                    JSONObject response = new JSONObject(succ);
                    JSONObject data = response.getJSONObject(HttpUtils.UPLOAD_DATA);
                    JSONArray results = data.getJSONArray("results");
                    List<TagItem> acgItemList = gson.fromJson(results.toString(), new TypeToken<List<TagItem>>() {
                    }.getType());
                    for (TagItem a : acgItemList) {
                        if (!isTagnameRepeated(a, wlist)) {
                            SearchContent searchContent1 = new SearchContent(a);
                            searchContent1.setOtype("tag");
                            tagsList.add(searchContent1);
                        }
                    }
                    tagCount = data.getInt("total");
                    isWorkEnd = true;
                    checkEnd();
                } catch (Exception e) {
                    isWorkEnd = true;
                    checkEnd();
                }
            }

            @Override
            public void fail(String type) {
                mProgressbarHelper.onFailed();
            }
        });
        searchHelper.getSearch("tag", page, query);
    }

    private void getUser() {
        SearchHelper searchHelper = new SearchHelper(getActivity(), new ISearchhelper() {
            @Override
            public void succ(String type, String succ) {
                try {
                    Gson gson = new Gson();
                    JSONObject response = new JSONObject(succ);
                    JSONObject data = response.getJSONObject(HttpUtils.UPLOAD_DATA);
                    JSONArray results = data.getJSONArray("results");
                    userCount = data.getString("total");
                    userList = gson.fromJson(results.toString(), new TypeToken<List<SearchContent>>() {
                    }.getType());
                    isUserEnd = true;
                    checkEnd();
                } catch (Exception e) {
                    isUserEnd = true;
                    checkEnd();
                }
            }

            @Override
            public void fail(String type) {
                mProgressbarHelper.onFailed();
            }
        });
        searchHelper.getSearch("user", page, query, "4");
    }

    private void checkEnd() {
        if (isWorkEnd && isUserEnd && isDataEnd) {
            List<SearchContent> templist = new ArrayList<>();
            if (page == 1) {
                initWorkUser(templist);
                if (templist.size() >= 2 && tagsList != null && !tagsList.isEmpty()) {
                    int resultCount = workCount + tagCount;
                    templist.get(0).setIs_show(true);
                    templist.get(1).setIs_show(true);
                    templist.get(0).setTitle_num_format(String.format(getString(R.string.releated_work_pink), String.valueOf(resultCount)));
                    templist.get(1).getCircleContents().addAll(tagsList);
                }
                if (templist.size() >= 4 && userList != null && !userList.isEmpty()) {
                    templist.get(2).setIs_show(true);
                    templist.get(3).setIs_show(true);
                    templist.get(2).setTitle_num_format(String.format(getString(R.string.releated_user_pink), userCount));
                    templist.get(3).getUserContents().addAll(userList);
                }
            }
            templist.addAll(contentList);
            dealResult(templist);
        }
    }

    private boolean isTagnameRepeated(TagItem tagItem, List<SearchContent> workList) {
        boolean repeatFlag = false;
        for (SearchContent searchContent : workList) {
            if (tagItem.getName().equals(searchContent.getAcgItem().getReal_name())) {
                repeatFlag = true;
                break;
            }
        }
        return repeatFlag;
    }

    private void getCos() {
        SearchHelper searchHelper = new SearchHelper(getActivity(), new ISearchhelper() {
            @Override
            public void succ(String type, String succ) {
                try {
                    Gson gson = new Gson();
                    List<SearchContent> templist = new ArrayList<SearchContent>();
                    JSONObject response = new JSONObject(succ);
                    JSONObject data = response.getJSONObject(HttpUtils.UPLOAD_DATA);
                    JSONArray results = data.getJSONArray("results");
                    if (page == 1) {
                        String count = data.getString("total");
                        SearchContent searchContent = new SearchContent();
                        searchContent.setTitle_num_format(String.format(getString(R.string.releated_cos_pink), count));
                        searchContent.setIs_show(true);
                        templist.add(searchContent);
                    }
                    List<Timeline> cosList = gson.fromJson(results.toString(), new TypeToken<List<Timeline>>() {
                    }.getType());
                    templist.addAll(saveToInnerList(SearchHelper.popIllegal(cosList, new int[]{TimelineFactory.TIMELINE_TYPE_COSER})));
                    dealResult(templist);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void fail(String type) {
                mProgressbarHelper.onFailed();
            }
        });
        searchHelper.getSearch("cos", page, query);
    }

    private void getDraw() {
        SearchHelper searchHelper = new SearchHelper(getActivity(), new ISearchhelper() {
            @Override
            public void succ(String type, String succ) {
                try {
                    Gson gson = new Gson();
                    List<SearchContent> templist = new ArrayList<SearchContent>();
                    JSONObject response = new JSONObject(succ);
                    JSONObject data = response.getJSONObject(HttpUtils.UPLOAD_DATA);
                    JSONArray results = data.getJSONArray("results");
                    if (page == 1) {
                        String count = data.getString("total");
                        SearchContent searchContent = new SearchContent();
                        searchContent.setTitle_num_format(String.format(getString(R.string.releated_draw_pink), count));
                        searchContent.setIs_show(true);
                        templist.add(searchContent);
                    }
                    List<Timeline> drawList = gson.fromJson(results.toString(), new TypeToken<List<Timeline>>() {
                    }.getType());
                    templist.addAll(saveToInnerList(SearchHelper.popIllegal(drawList, new int[]{TimelineFactory.TIMELINE_TYPE_ILLUST})));
                    dealResult(templist);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void fail(String type) {
                mProgressbarHelper.onFailed();
            }
        });
        searchHelper.getSearch("illust", page, query);
    }

    private void getNovel() {
        SearchHelper searchHelper = new SearchHelper(getActivity(), new ISearchhelper() {
            @Override
            public void succ(String type, String succ) {
                try {
                    Gson gson = new Gson();
                    List<SearchContent> templist = new ArrayList<SearchContent>();
                    JSONObject response = new JSONObject(succ);
                    JSONObject data = response.getJSONObject(HttpUtils.UPLOAD_DATA);
                    JSONArray results = data.getJSONArray("results");
                    if (page == 1) {
                        String count = data.getString("total");
                        SearchContent searchContent = new SearchContent();
                        searchContent.setTitle_num_format(String.format(getString(R.string.releated_write_pink), count));
                        searchContent.setIs_show(true);
                        templist.add(searchContent);
                    }
                    List<Timeline> novelList = gson.fromJson(results.toString(), new TypeToken<List<Timeline>>() {
                    }.getType());
                    templist.addAll(saveToInnerList(SearchHelper.popIllegal(novelList, new int[]{TimelineFactory.TIMELINE_TYPE_WRITER})));
                    dealResult(templist);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void fail(String type) {
                mProgressbarHelper.onFailed();
            }
        });
        searchHelper.getSearch("write", page, query);
    }

    private void getGoods() {
        SearchHelper searchHelper = new SearchHelper(getActivity(), new ISearchhelper() {
            @Override
            public void succ(String type, String succ) {
                try {
                    Gson gson = new Gson();
                    List<SearchContent> templist = new ArrayList<>();
                    JSONObject response = new JSONObject(succ);
                    JSONObject data = response.getJSONObject(HttpUtils.UPLOAD_DATA);
                    JSONArray results = data.getJSONArray("results");
                    if (page == 1) {
                        String count = data.getString("total");
                        SearchContent searchContent = new SearchContent();
                        searchContent.setTitle_num_format(String.format(getString(R.string.releated_goods_pink), count));
                        searchContent.setIs_show(true);
                        templist.add(searchContent);
                    }
                    List<Timeline> goodslList = gson.fromJson(results.toString(), new TypeToken<List<Timeline>>() {
                    }.getType());
                    templist.addAll(saveToInnerList(SearchHelper.popIllegal(goodslList, new int[]{TimelineFactory.TIMELINE_TYPE_GOODS})));
                    dealResult(templist);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void fail(String type) {
                mProgressbarHelper.onFailed();
            }
        });
        searchHelper.getSearch("goods", page, query);
    }

    private void getDaily() {
        SearchHelper searchHelper = new SearchHelper(getActivity(), new ISearchhelper() {
            @Override
            public void succ(String type, String succ) {
                try {
                    Gson gson = new Gson();
                    List<SearchContent> templist = new ArrayList<SearchContent>();
                    JSONObject response = new JSONObject(succ);
                    JSONObject data = response.getJSONObject(HttpUtils.UPLOAD_DATA);
                    JSONArray results = data.getJSONArray("results");
                    if (page == 1) {
                        String count = data.getString("total");
                        SearchContent searchContent = new SearchContent();
                        searchContent.setTitle_num_format(String.format(getString(R.string.releated_daily_pink), count));
                        searchContent.setIs_show(true);
                        templist.add(searchContent);
                    }
                    List<Timeline> dailyList = gson.fromJson(results.toString(), new TypeToken<List<Timeline>>() {
                    }.getType());
                    templist.addAll(saveToInnerList(SearchHelper.popIllegal(dailyList, new int[]{TimelineFactory.TIMELINE_TYPE_DAILY})));
                    dealResult(templist);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void fail(String type) {
                mProgressbarHelper.onFailed();
            }
        });
        searchHelper.getSearch("daily", page, query);
    }


    private List<SearchContent> saveToInnerList(List<Timeline> glist) {
        List<SearchContent> templist = new ArrayList<SearchContent>();
        for (int i = 0; i < glist.size(); i++) {
            templist.add(new SearchContent(glist.get(i)));
        }
        return templist;
    }

    @Override
    protected void initData() {
        loading = true;
        if (StringUtil.notNullEqual(filter_name, "content")) {
            getContent();
            if (page == 1) {
                getWork();
                getUser();
            }
        } else if (StringUtil.notNullEqual(filter_name, "coser")) {
            getCos();
        } else if (StringUtil.notNullEqual(filter_name, "drawer")) {
            getDraw();
        } else if (StringUtil.notNullEqual(filter_name, "daily")) {
            getDaily();
        } else if (StringUtil.notNullEqual(filter_name, "writer")) {
            getNovel();
        } else if (StringUtil.notNullEqual(filter_name, "goods")) {
            getGoods();
        }
    }

    private void initWorkUser(List<SearchContent> templist) {

        SearchContent workCount = new SearchContent();
        workCount.setTitle_num_format(String.format(getString(R.string.releated_work_pink), "0"));
        workCount.setIs_show(false);
        templist.add(workCount);

        SearchContent wlist = new SearchContent();
        wlist.setOtype("circles");
        wlist.setCircleContents(new ArrayList<SearchContent>());
        wlist.setIs_show(false);
        templist.add(wlist);

        SearchContent userCount = new SearchContent();
        userCount.setTitle_num_format(String.format(getString(R.string.releated_user_pink), "0"));
        userCount.setIs_show(false);
        templist.add(userCount);

        SearchContent ulist = new SearchContent();
        ulist.setOtype("users");
        ulist.setUserContents(new ArrayList<SearchContent>());
        ulist.setIs_show(false);
        templist.add(ulist);
    }

    private void dealResult(List<SearchContent> tempList) {
        ll_nodata.setVisibility(View.GONE);
        if (page == 1) {
            slist.clear();
        }
        if (tempList.size() == 0) {
            end_flag = true;
        }
        int startListCount = slist.size();
        slist.addAll(tempList);
        if (page == 1) {
            mAdapter.notifyDataSetChanged();
        } else {
            mAdapter.notifyItemRangeInserted(startListCount, tempList.size());
        }
        mRefreshLv.onRefreshComplete();
        mProgressbarHelper.onSuccess();
        loading = false;
    }

    private void initAdapter() {
        mAdapter = new SearchContentAdapter(slist, getActivity());
    }

}
